"""K8s提取器YAML处理工具模块"""

import yaml
import json
from typing import Dict, Any, Optional
import logging
import os

logger = logging.getLogger(__name__)

def load_yaml(content: str, default: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    """
    加载YAML内容为Python字典
    
    Args:
        content: YAML格式的字符串
        default: 默认返回值，如果解析失败
        
    Returns:
        解析后的字典
    """
    if default is None:
        default = {}
        
    if not content:
        return default
        
    try:
        return yaml.safe_load(content) or default
    except yaml.YAMLError as e:
        logger.error(f"YAML解析失败: {str(e)}")
        return default

def load_yaml_file(file_path: str, default: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    """
    从文件中加载YAML内容为Python字典
    
    Args:
        file_path: YAML文件路径
        default: 默认返回值，如果解析失败
        
    Returns:
        解析后的字典
    """
    if default is None:
        default = {}
        
    if not os.path.exists(file_path):
        logger.error(f"YAML文件不存在: {file_path}")
        return default
        
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        return load_yaml(content, default)
    except Exception as e:
        logger.error(f"读取YAML文件失败: {file_path}, 错误: {str(e)}")
        return default

def load_json(content: str, default: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    """
    加载JSON内容为Python字典
    
    Args:
        content: JSON格式的字符串
        default: 默认返回值，如果解析失败
        
    Returns:
        解析后的字典
    """
    if default is None:
        default = {}
        
    if not content:
        return default
        
    try:
        return json.loads(content) or default
    except json.JSONDecodeError as e:
        logger.error(f"JSON解析失败: {str(e)}")
        return default

def load_json_file(file_path: str, default: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    """
    从文件中加载JSON内容为Python字典
    
    Args:
        file_path: JSON文件路径
        default: 默认返回值，如果解析失败
        
    Returns:
        解析后的字典
    """
    if default is None:
        default = {}
        
    if not os.path.exists(file_path):
        logger.error(f"JSON文件不存在: {file_path}")
        return default
        
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        return load_json(content, default)
    except Exception as e:
        logger.error(f"读取JSON文件失败: {file_path}, 错误: {str(e)}")
        return default

def dump_yaml(data: Dict[str, Any], default_flow_style: bool = False) -> str:
    """
    将Python字典转换为YAML格式字符串
    
    Args:
        data: 要转换的字典
        default_flow_style: 是否使用默认流风格
        
    Returns:
        YAML格式的字符串
    """
    try:
        return yaml.dump(data, default_flow_style=default_flow_style, sort_keys=False)
    except Exception as e:
        logger.error(f"转换为YAML字符串失败: {str(e)}")
        return ""

def dump_yaml_file(data: Dict[str, Any], file_path: str, default_flow_style: bool = False) -> bool:
    """
    将Python字典保存为YAML文件
    
    Args:
        data: 要保存的字典
        file_path: 输出文件路径
        default_flow_style: 是否使用默认流风格
        
    Returns:
        是否成功保存
    """
    try:
        # 确保目录存在
        os.makedirs(os.path.dirname(os.path.abspath(file_path)), exist_ok=True)
        
        with open(file_path, 'w', encoding='utf-8') as f:
            yaml.dump(data, f, default_flow_style=default_flow_style, sort_keys=False)
        logger.debug(f"已保存YAML文件: {file_path}")
        return True
    except Exception as e:
        logger.error(f"保存YAML文件失败: {file_path}, 错误: {str(e)}")
        return False

def merge_dicts(dict1: Dict[str, Any], dict2: Dict[str, Any]) -> Dict[str, Any]:
    """
    合并两个字典，dict2的值会覆盖dict1中的相同键
    
    Args:
        dict1: 第一个字典
        dict2: 第二个字典
        
    Returns:
        合并后的字典
    """
    result = dict1.copy()
    
    for key, value in dict2.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = merge_dicts(result[key], value)
        else:
            result[key] = value
            
    return result

def detect_format(content: str) -> str:
    """
    检测字符串内容是YAML格式还是JSON格式
    
    Args:
        content: 要检测的字符串内容
        
    Returns:
        'yaml', 'json' 或 'unknown'
    """
    # 去除前导空白
    content = content.strip()
    
    # 尝试解析为JSON
    try:
        json.loads(content)
        return 'json'
    except json.JSONDecodeError:
        pass
        
    # 尝试解析为YAML
    try:
        yaml.safe_load(content)
        return 'yaml'
    except yaml.YAMLError:
        pass
        
    return 'unknown'
